package ru.demo.abstarctservice.adapter.rabbit;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;


@Slf4j
@Service
@RequiredArgsConstructor
public class RabbitMQChangesProducer {

    private final RabbitTemplate rabbitTemplate;
    private final RabbitMQProperties properties;
    private final ObjectMapper objectMapper;

    @SneakyThrows
    @EventListener
    public void produce(RabbitMQEvent<?> rabbitMQEvent) {
        String routingKey = rabbitMQEvent.getRoutingKey();
        log.debug("Сообщение по ключу {} отправлено в rabbitMQ в exchange {}",
                routingKey, properties.getChangesExchange());
        rabbitTemplate.convertAndSend(properties.getChangesExchange(), routingKey, getMessage(rabbitMQEvent));
    }

    private Message getMessage(RabbitMQEvent<?> rabbitMQEvent) throws JsonProcessingException {
        return MessageBuilder
                .withBody(objectMapper.writeValueAsBytes(rabbitMQEvent.getEntityDto()))
                .setMessageId(rabbitMQEvent.getClassName())
                .setContentType("application/json")
                .setReceivedRoutingKey(rabbitMQEvent.getRoutingKey())
                .setContentEncoding("utf-8")
                .setHeader("operation", rabbitMQEvent.getOperation())
                .build();
    }
}
